<?php
/**
 * @Author: feidao@ibantang.com, 2019, all rights reserved
 * @Date: 2019-07-30
 * @Time: 15:07
 * @Brief:
 */

namespace Core\Common\Helper;

use Core\Common\Base\RoundRobin;
use Core\Common\Base\Service;

class GatewayService
{
    // 网关支持的协议类型
    const PROTO_HTTP = "http";
    const PROTO_GRPC = "grpc";
    const PROTO_TCP = "tcp";
    const PROTO_WEBSOCKET = "ws";

    /**
     * 获取网关地址
     * @param string $gatewayName 网关名 如: sqkb-fabio
     * @param string $proto http|tcp|grpc|ws
     * @return array|null
     */
    public static function getService(string $gatewayName, string $proto)
    {
        $gatewayName = trim($gatewayName);
        $proto = trim($proto);
        if (empty($gatewayName) || empty($proto)) {
            return null;
        }

        $targets = Service::getService($gatewayName, $proto);
        if ($targets && is_array($targets)) {
            $c = count($targets);
            if (1 == $c) {
                return $targets[0];
            }

            $serviceId = Service::getServiceId($gatewayName, $proto);
            $index = RoundRobin::incr($serviceId);
            return $targets[$index % $c];
        }
        return null;
    }
}
